--
-- @Author:      name
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 机器人管理

local skynet = require "skynet"
local harbor = require "skynet.harbor"
local log = require "Log"
local Network = require "Network"

local common = require "common"
local NodeMessage = require "NodeMessage"
require "util"
require "setting"

local AccountManager = class("AccountManager")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function AccountManager:ctor(message)	
	--随机种子
    local time = tostring(os.time())
    math.randomseed(time:reverse():sub(1, 7))	
	local svrConfig = robot_backstage	
	self.msg = message
	self.ip = svrConfig.ip
	self.port = svrConfig.port
	self.tbUsergame = { name="usergame", pk='uid',key='uid', indexkey='' }
	self.tbRobotOnline = { name="robot_online", pk='uid',key='uid', indexkey='' }
	local backstagePort = skynet.getenv("backstage_port")
	if backstagePort and #backstagePort>1 then 
		self.port = backstagePort
	end
	print("____self.port___",self.port)
	self.nodeMessage = NodeMessage.new()
	--数据库服务 
	--数据库服务 
	local mysqldata = {host = skynet.getenv("mysql_host"),
				  port = skynet.getenv("mysql_port"),				  
				  user = skynet.getenv("mysql_user"),
				  password = skynet.getenv("mysql_pwd"),
				  database = skynet.getenv("mysql_db"),
				  serviceName = "mysql_service",
				 }
	self.mysql = skynet.newservice("mysql_service")
	skynet.call(self.mysql, "lua", "start", mysqldata)

	--log数据库服务 
	local logData = {host = skynet.getenv("mysql_host"),
				  port = skynet.getenv("mysql_port"),				  
				  user = skynet.getenv("mysql_user"),
				  password = skynet.getenv("mysql_pwd"),
				  database = "qicaipoker_log",
				  serviceName = "mysql_log",
				 }
	self.mysqlLog = skynet.newservice("mysql_service")
	skynet.call(self.mysqlLog, "lua", "start", logData)
	
	-- self.redis = skynet.uniqueservice("redis_service")
	-- skynet.call(self.redis, "lua", "start")
	--开启网络模块
	self.network = Network.new(self.ip,self.port)
	--在线列表
	self.tbOnline = {}
	--离线
	self.tbOffline = {}


	self:initAccount()
	--注册消息回调
	self:register()
	print("___________######____")
	self.robotName = skynet.getenv("robot_name")
	if skynet.getenv("robot_name") == "paodekuai" then
		local data = {gameid=14,roomid=141,tableid=141000001}
		self:addRobot(data)	
	end
	if skynet.getenv("robot_name") == "paohuzi" then
		local data = {gameid=6,roomid=60,tableid=60000002,num=3}
		self:addRobot(data)

	end	
	-- self:getAccount(3)
	-- self:clearOnline()
end

function AccountManager:register()
	self.network:register('socket_close',handler(self,self.socketClose))
	self.network:register('rb_nt_add',handler(self,self.addRobot))
	self.network:register('rb_nt_online',handler(self,self.online))
	self.network:register('rb_nt_offline',handler(self,self.offline))

	self.msg:registerSelf('rb_get_account',handler(self,self.getAccount))
	self.msg:registerSelf('change_money',handler(self,self.changeMoney))	
end

function AccountManager:socketClose()
	print("________服务器断线_________")
	--把在线的号设置为离线
	self:clearOnline()
end
--加载机器人账号表
function AccountManager:initAccount()
	-- local tb = self:loadMysqlData(self.tbUsergame,{"uid","uchip"})
	local tb 
	local sql1 = 'select uid from robot_online where uid='
	local sql2 = 'insert into robot_online (uid) value('
	local res
	tb = skynet.call(self.mysql, "lua", "execute", "select uid from usergame where (uid>4995000)and(uid<4996000) and (uid in (select uid from userinfo));")
	for k,v in pairs(tb) do 		
		-- print("____>",v,k)
		res = skynet.call(self.mysql, "lua", "execute", sql1 ..v.uid)
		if not res or not next(res) then 
			res = skynet.call(self.mysql, "lua", "execute", sql2 ..v.uid ..')')
		end
	end
	-- tb = self:loadMysqlData(self.tbRobotOnline)
	tb = skynet.call(self.mysql, "lua", "execute", "select * from robot_online where (uid>4995000)and(uid<4996000);")
	for k,v in pairs(tb) do 
		if v.online==1 or v.tableid>0 then 
			-- self.tbOnline[v.uid] = v
		else
			self.tbOffline[v.uid] = v
		end
	end
	-- print("___tbOnline__",self.tbOnline)
	-- print("___tbOffline__",self.tbOffline)
end

--加载表数据
function AccountManager:loadMysqlData(tableInfo, field)
	local tbname = tableInfo.name
	local pk = tableInfo.pk
	local key = tableInfo.key
	local offset = 0
	local sql
	local data = {}
	if not field then
		sql = string.format("select * from %s order by %s asc limit %d, 1000", tbname, pk, offset)
	else
		local strField
		for k,v in pairs(field) do 
			if not strField then 
				strField = v
			else
				strField = strField ..','..v
			end
		end
		sql = string.format("select "..strField.." from %s  where (uid<5000000) order by %s asc limit %d, 1000", tbname, pk, offset)
	end
	local rs = skynet.call(self.mysql, "lua", "execute", sql)
	if #rs <= 0 then 
		print(tbname.."____表为空___")
		return data
	end
	for _, row in pairs(rs) do
		table.insert(data, row)			
	end
	return data
end

--获取离线机器人id
function AccountManager:getAccount(num)
	local n = 0
	local tb = skynet.call(self.mysql, "lua", "execute", "select * from robot_online where (uid>4995000)and(uid<4996000);")
	for k,v in pairs(tb) do 
		if v.online==0 or v.tableid==0 then 
			self.tbOffline[v.uid] = v
		end
	end
	local tbPlayer = {}
	for k,v in pairs(self.tbOffline) do 
		if tonumber(v.online)==0 and tonumber(v.tableid)==0 then
			n=n+1 
			table.insert(tbPlayer,v)
			self.tbOffline[k] = nil
			if n >= num then 
				break
			end
		end
	end
	print("_______tbPlayer__",tbPlayer)
	return tbPlayer
end

--对指定场，桌加入机器人
function AccountManager:addRobot(data)
	print("__11__addRobot_____",data)
	local gameid = data.gameid
	local roomid = data.roomid
	local tableid = data.tableid
	local num = data.num or 1
	local svrname
	local players
	players = self:getAccount(num)
	if not next(players) then
		print("____取不到机器人___",self.tbOffline)
		return 
	end
	if gameid == 14 or gameid == 6 then 
		-- players = {
		-- 	 {
		-- 		uid     = 4995002,
		-- 		online  = 0,
		-- 		tableid = 0,
		-- 	},
		-- 	 {
		-- 		uid     = 4995004,
		-- 		online  = 0,
		-- 		tableid = 0,
		-- 	},
		-- 	{
		-- 		uid     = 4995006,
		-- 		online  = 0,
		-- 		tableid = 0,
		-- 	},
		-- }
		if not next(players) then
			print("____取不到机器人___",self.tbOffline)
			return 
		end
		print("___self.robotName__",self.robotName)
		skynet.uniqueservice(self.robotName)
		self.nodeMessage:sendService(self.robotName,'add_robot',data,players)
	elseif gameid == 10 then
		svrname = 'pinshi'
		skynet.uniqueservice(svrname)
		self.nodeMessage:sendService(svrname,'add_robot',data,players)
	end
end

--
function AccountManager:online(param)
	print("____online__",param)
	local playerid = param.playerid
	if not playerid then 
		return 
	end
	local player = self.tbOnline[playerid]
	if not player then 
		self.tbOnline[playerid] = {playerid=playerid,online=0,tableid=0}
		player = self.tbOnline[playerid]
	end
	if param.online then 
		player.online = param.online
	elseif param.tableid then 
		player.tableid = param.tableid
	end

end

function AccountManager:offline(param)
	print("____offline__",param)
	local playerid = param.playerid
	if not playerid then 
		return 
	end
	local player = self.tbOffline[playerid]
	if not player then 
		player = {online=0,tableid=0}
	end
	if param.online then 
		player.online = param.online
	elseif param.tableid then 
		player.tableid = param.tableid
	end
end

function AccountManager:clearOnline()
	local sql = 'update robot_online set online=0,tableid=0 where uid='
	local res 
	for k,v in pairs(self.tbOnline) do 
		res = skynet.call(self.mysql, "lua", "execute", sql ..k)
	end	
	self.tbOnline = {}
end

function AccountManager:changeMoney(data)
	local playerid = data.playerid
	local robotType = data.robotType
	--金币不够入处理			

	local sql1 = string.format("select * from usergame where uid = %d", data.uid)
	local res1 = skynet.call("mysql_service", "lua", "execute", sql1)
	local sql2 = string.format("update usergame set uchip=uchip + %d where uid=%d", data.money, data.uid)
	local res2 = skynet.call("mysql_service", "lua", "execute", sql2)

	local tableName = "robot_coin_log" .. os.date("%Y%m%d")
	--local sqlCreateTable = string.format("create table if not exists %s like robot_coin_log;", tableName)
	--local res =  skynet.call("mysql_log", "lua", "execute", sqlCreateTable)
	local sqlInsert = string.format("insert into %s (uid, coin, code, time, game, gameid, gametype) values (%d, %d, %d, %d, %d, %d, %d);",
	tableName, data.uid, data.money, data.code, os.time(), data.game or 0, data.gameid, data.gametype)
	skynet.call("mysql_log", "lua", "execute", sqlInsert)
	--[[local data = {
		rb_change_money_req={
			playerid = playerid,
			diamond = self.tbAddMoney[robotType],
			}
		}
	self.network:send(data)]]--
	--print("___addmoney___________",data)	

end
return AccountManager